package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"net/http"
	"os"
	"strconv"
	"sync"
)
const(
	muti=4 //线程数
)

var url= "http://localhost/yiifront/test.avi"
var mutex sync.Mutex
var wg = sync.WaitGroup{}

func main(){
	fmt.Println("start download...")
	filesize:=getfilelenth()

	f, err := os.Create("./output3.avi") //创建文件
	if err!=nil{
		panic(err)
	}

	part:=filesize/muti+1
	wg.Add(muti)
	for i:=0;i<muti;i++{
		go download(f,filesize,part,i)
	}
	defer f.Close()
	wg.Wait()
}

func download(file *os.File,filesize int64,part int64,i int){
	fmt.Println("start zhe download:"+strconv.Itoa(i))
	mutex.Lock()
	client := &http.Client{}
	req, err := http.NewRequest("GET", url, nil)
	var start ,end int64
	if i!=0{
		start=int64(i)*part+1
	}else{
		start=int64(i)*part
	}
	if i+1==muti{
		end=filesize
	}else{
		end=int64(i+1)*part
	}
    str:=strconv.FormatInt(start,10)+"-"+strconv.FormatInt(end,10) //+"/"+strconv.FormatInt(filesize,10)
	fmt.Println("Range"+strconv.Itoa(i),"bytes="+str)
	req.Header.Set("Range","bytes="+str)
	resp, err := client.Do(req)
	if err != nil {
		log.Printf("client.Do err: %v", err)
	}
	//fmt.Println("response Status:", resp.Status)
	fmt.Println("response length:"+strconv.Itoa(i)+":", resp.Header.Get("Content-Length"))
	//fmt.Println("response Range:", resp.Header.Get("Accept-Ranges"))
	op,err:=file.Seek(start,0)
	fmt.Println("response length:", op)
	body, err := ioutil.ReadAll(resp.Body)
	if err!=nil{
		log.Printf("read file error: %v", err)
	}
	if len(body)==0{
		fmt.Println("no file")
	}else{
       fmt.Println(resp.ContentLength)
	}
	wg.Done()
	len,err:=file.Write(body)
	fmt.Println("write file:"+strconv.Itoa(i)+":",len)
	resp.Body.Close()
	mutex.Unlock()
}

func getfilelenth()int64{
	/***
	post := `{"LoginForm[username]": "admin", "LoginForm[password]": "admin","LoginForm[rememberMe]":"1"}`
	fmt.Println(url, "post", post)

	var jsonStr = []byte(post)
	fmt.Println("jsonStr", jsonStr)
	fmt.Println("new_str", bytes.NewBuffer(jsonStr))

	req, err := http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
	if err!=nil{
		panic(err)
	}
	// req.Header.Set("X-Custom-Header", "myvalue")
	req.Header.Set("Content-Type", "application/x-www-form-urlencoded")

	client := &http.Client{}
	resp, err := client.Do(req)
	***/
	client := &http.Client{}
	req, err := http.NewRequest("HEAD", url, nil)
	if err != nil {
		log.Printf("http.NewRequest err: %v", err)
	}
	resp, err := client.Do(req)
	if err != nil {
		log.Printf("client.Do err: %v", err)
	}
	//fmt.Println(resp.Header.Get("Accept-Ranges"))
	//fmt.Println(resp.Header.Get("Content-Type"))
	return resp.ContentLength
}
